package com.yand.frame.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yand.frame.dao.ActivityRoleMapper;
import com.yand.frame.dao.UserDao;
import com.yand.frame.dto.user.UserDto;
import com.yand.frame.entity.ActivityRole;
import com.yand.frame.entity.ActivityUser;
import com.yand.frame.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserDao userDao;

    @Autowired
    private ActivityRoleMapper activityRoleMapper;

    @Override
    public PageInfo getUserList(UserDto dto) {

        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());

        return PageInfo.of(userDao.getActivityUserList(dto));
    }


    @Override
    public List<ActivityRole> getAllRole() {
        return activityRoleMapper.queryRoleList(null);
    }

    @Override
    public void addUser(ActivityUser user) {
        String password = DigestUtils.md5DigestAsHex(user.getrPassword().getBytes());
        //添加默认密码
        user.setrPassword(password);

        //获取当前时间的格式化字符串
        String now  = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());

        user.setExtension5(now);

        userDao.insert(user);

    }

    @Override
    public void deleteUser(Integer id) {

        userDao.delete(id);
    }

    @Override
    public boolean validateOldPass(String oldPass) {
        //获取密码
        String password = DigestUtils.md5DigestAsHex(oldPass.getBytes());
        //获取当前登录人
        ActivityUser activityUser = (ActivityUser)SecurityUtils.getSubject().getPrincipal();
        if(password.equals(activityUser.getrPassword())){
          return true;
        }
        return false;
    }

    @Override
    public void updatePassword(String password) {
        //获取当前登录人
        ActivityUser activityUser = (ActivityUser)SecurityUtils.getSubject().getPrincipal();
        //获取密码
        String newPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        activityUser.setrPassword(newPassword);

        userDao.udpatePass(activityUser);
    }


}
